<template>
  <div class="addContract">
    <!-- <h4>新增合同</h4> -->
    <el-dialog :title="mode=='add'?'新增':'编辑'"
               class="addTask"
               width='850px'
               :close-on-click-modal="true"
               :visible.sync="visible">
      <!-- 具体表单 -->
      <el-form :model="dataForm"
               :rules="dataRule"
               ref="dataForm"
               @keyup.enter.native="dataFormSubmit()"
               label-width="120px">
        <el-form-item label="企业id"
                      v-if="workerIdVisb"
                      prop="cid">
          <el-input v-model="dataForm.cid"
                    placeholder="企业id"></el-input>
        </el-form-item>
        <el-form-item label="编号"
                      prop="contractNum">
          <el-input v-model="dataForm.contractNum"
                    placeholder="编号"></el-input>
        </el-form-item>
        <!-- <el-form-item label="创建者"
                      prop="createUser">
          <el-input v-model="dataForm.createUser"
                    placeholder="创建者"></el-input>
        </el-form-item> -->
        <el-form-item label="合同名称"
                      prop="contractName">
          <el-input v-model="dataForm.contractName"
                    placeholder="合同名称"></el-input>
        </el-form-item>
        <el-form-item label="合同内容"
                      prop="contractText">
          <!-- <el-input v-model="dataForm.contractText"
                  placeholder="合同内容"></el-input> -->
          <!-- <script :id="this.ueId"
                  name="content"
                  type="text/plain">
            这里写你的初始化内容
          </script> -->
          <script :id="ueId"
                  class="ueditor-box"
                  type="text/plain"
                  style="width: 100%; height: 260px;">请在这里书写个人协议相关内容</script>
        </el-form-item>
        <!-- <el-form-item label="缴纳时间"
                    prop="taxPayTime">
        <el-date-picker v-model="dataForm.taxPayTime"
                        type="date"
                        placeholder="缴纳时间"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item> -->
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   class="btn"
                   @click="addSave"
                   v-if="mode == 'add'">确认新增</el-button>
        <el-button type="primary"
                   class="btn"
                   @click="update"
                   v-else>确认修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ueditor from 'ueditor'
export default {
  data () {
    return {
      // 判断添加还是编辑
      mode: 'add',
      workerIdVisb: true,
      // 隐藏
      visible: false,
      // 数据
      dataForm: {
        // contractText: `J_ueditorBox_${new Date().getTime()}`
        contractText: ''
      },
      // 验证
      dataRule: {
        contractNum: [
          { required: true, message: '编号不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 编号正则校验
              let _reg = /^\d+$/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('编号只能为数字'))
              }
            }
          }
        ],
        contractName: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' }
        ]
      },
      // 富文本编辑器
      ue: null,
      ueId: `J_ueditorBox_${new Date().getTime()}`,
      ueContent: '',
      serverUrl: '',
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    }
  },
  created () {
    if (sessionStorage.getItem('userRoleId') === '2') {
      this.workerIdVisb = false
    }
  },
  mounted () {
    // console.log('mounted')
  },
  beforeUpdate () {
    this.$nextTick(() => {
      // console.log('beforeUpdate')
      try {
        this.serverUrl = this.$baseUrl + '/sys/contract/update'
        let url = this.serverUrl
        this.ue = ueditor.getEditor(this.ueId, {
          serverUrl: url, // 服务器统一请求接口路径
          zIndex: 3000
        })
      } catch (error) {
        // console.log(error)
      }
    })
  },
  methods: {
    // 父调用的方法，新增
    addInit () {
      this.visible = true
      try {
        this.ue.setContent('请在这里书写个人协议相关内容')
      } catch (error) {
        // console.log(error)
      }
    },
    // 父调用的方法，编辑
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      // console.log(this.ue)
      this.$nextTick(() => {
        // 设置编辑器的内容
        this.$http({
          url: this.$http.adornUrl('/sys/contract/info/' + id),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          // console.log(data.usageProtocol.content)
          // console.log(this.ue)
          this.ue.ready(() => {
            this.dataForm = data.sysContract
            // console.log(data.sysContract.contractText)
            this.ue.setContent(data.sysContract.contractText)
          })
        })
      })
    },
    // 新增
    addSave () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.ue.ready(() => {
            this.dataForm.contractText = this.ue.getContent()
            this.$http({
              url: this.$http.adornUrl('/sys/contract/save'),
              method: 'post',
              data: this.$http.adornParams(
                this.dataForm
              )
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    // 成功之后的回调
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          })
        }
      })
    },
    // 修改提交
    update () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.ue.ready(() => {
            this.dataForm.contractText = this.ue.getContent()
            this.$http({
              url: this.$http.adornUrl('/sys/contract/update'),
              method: 'post',
              data: this.$http.adornParams(this.dataForm)
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    // 成功之后的回调
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          })
        }
      })
    }
    // 结束
  }
}
</script>

<style lang="scss">
.addContract {
  .el-input.el-input--medium {
    width: 370px;
  }
  .el-dialog__header {
    background-color: #f8f8f8;
  }
  .el-dialog__body {
    display: flex;
    justify-content: center;
  }
  .btn {
    width: 370px;
  }
  .dialog-footer {
    text-align: center !important;
    padding-bottom: 39px;
  }
  .el-dialog__footer {
    text-align: center;
    padding-bottom: 39px;
  }
  // 富文本
  .mod-demo-ueditor {
    // position: relative;
    // z-index: 510;
    // > .el-alert {
    //   margin-bottom: 10px;
    // }
  }
}
</style>
